<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :close-on-click-modal="false" @close="handleClose">
    <div v-if="approvalData" class="approval-dialog">
      <!-- 审批信息展示 -->
      <div class="approval-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="审批编号">
            {{ approvalData.requestNo }}
          </el-descriptions-item>
          <el-descriptions-item label="审批类型">
            {{ approvalData.templateDescription || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="合同编号">
            {{ approvalData.cno || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="合同名称">
            <div class="info-item-with-link">
              <span>{{ approvalData.cname || '某合同一查看信息' }}</span>
              <el-link type="primary" @click="handleViewContract" style="margin-left: 30px;">查看信息</el-link>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="合同类型">
            {{ approvalData.ctype === 1 ? '工程类' : '直销类' }}
          </el-descriptions-item>
          <el-descriptions-item label="工程名称">
            {{ approvalData.projectName || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="关联需求编号">
            {{ approvalData.dno || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="关联需求">
            <div class="info-item-with-link">
              <span>{{ approvalData.dname || '' }}</span>
              <el-link type="primary" @click="handleViewRequirement" style="margin-left: 30px;">查看参数</el-link>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ approvalData.applicantName }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ parseTime(approvalData.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="2">
            {{ approvalData.content }}
          </el-descriptions-item>
          <el-descriptions-item label="附件" :span="2">
            <div class="info-item-with-link">
              <span>
                {{ approvalData.attachments.length > 0 ? approvalData.attachments : '无' }}
              </span>
              <div v-if="approvalData.attachments.length > 0">
                <el-link type="primary" @click="handlePreviewAttachment" style="margin-left: 30px;">预览</el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" @click="handleDownloadAttachment">下载</el-link>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮 -->
      <div v-if="mode === 'approve'" class="action-buttons">
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handleReject">驳回</el-button>
        <el-button type="primary" @click="handleApprove">通过</el-button>
      </div>

      <!-- 转交功能 -->
      <div v-if="mode === 'transfer' && showTransfer" class="transfer-section">
        <h4>转交</h4>
        <el-form :model="transferForm" :rules="transferRules" ref="transferFormRef" label-width="100px">
          <el-form-item label="转交对象" prop="transferTarget">
            <el-select v-model="transferForm.transferTarget" placeholder="请选择转交对象" style="width: 100%">
              <el-option-group label="技术部门">
                <el-option label="张三(zhangsan)" value="zhangsan" />
                <el-option label="李四(lisi)" value="lisi" />
              </el-option-group>
              <el-option-group label="分析部门">
                <el-option label="王五(wangwu)" value="wangwu" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="转交原因" prop="transferReason">
            <el-input v-model="transferForm.transferReason" type="textarea" :rows="3" placeholder="请输入转交原因，支持1-128个字符" maxlength="128" show-word-limit />
          </el-form-item>
        </el-form>
        <div class="transfer-buttons">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTransferConfirm">确定</el-button>
        </div>
      </div>

      <!-- 审批意见弹窗 -->
      <el-dialog v-model="commentDialogVisible" :title="commentType === 'approve' ? '通过' : '驳回'" width="500px" :close-on-click-modal="false" append-to-body>
        <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef" label-width="100px">
          <el-form-item label="审批意见" prop="comment">
            <el-input v-model="commentForm.comment" type="textarea" :rows="4" :placeholder="commentType === 'approve' ? '请输入审批意见' : '请输入驳回原因'" maxlength="128" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCommentCancel">取消</el-button>
            <el-button type="primary" @click="handleCommentConfirm">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 二级弹窗抽取为公共组件，改为向父组件派发事件由父级统一展示 -->
    </div>
  </el-dialog>
</template>

<script setup name="ApprovalDialog">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  approveApproval,
  rejectApproval,
} from '@/api/personCenter'
// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  approvalData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'approve'
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const mode = computed(() => props.mode)
const dialogTitle = computed(() => (mode.value === 'transfer' ? '转交' : '审批'))

// 转交相关
const showTransfer = ref(false)
const transferFormRef = ref()
const transferForm = reactive({
  transferTarget: '',
  transferReason: ''
})

const transferRules = {
  transferTarget: [{ required: true, message: '请选择转交对象', trigger: 'change' }],
  transferReason: [
    { required: true, message: '请输入转交原因', trigger: 'blur' },
    { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }
  ]
}

// 审批意见相关
const commentDialogVisible = ref(false)
const commentType = ref('approve') // 'approve' | 'reject'
const commentFormRef = ref()
const commentForm = reactive({
  comment: ''
})

const commentRules = {
  comment: [
    { required: true, message: '请输入审批意见', trigger: 'blur' },
    { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }
  ]
}

// 二级弹窗交由父级承载，这里仅派发事件

// 监听审批数据变化，判断是否显示转交
watch(
  () => props.approvalData,
  (newData) => {
    if (newData) {
      showTransfer.value = false
    }
  },
  { immediate: true }
)

// 根据模式控制转交区域显示
watch(
  () => [props.visible, mode.value],
  () => {
    showTransfer.value = mode.value === 'transfer'
  },
  { immediate: true }
)

// 关闭弹窗
const handleClose = () => {
  showTransfer.value = false
  commentDialogVisible.value = false
  resetForms()
}

// 重置表单
const resetForms = () => {
  Object.assign(transferForm, {
    transferTarget: '',
    transferReason: ''
  })
  Object.assign(commentForm, {
    comment: ''
  })
}

// 查看合同信息
const handleViewContract = () => {
  emit('view-info', props.approvalData)
}

// 查看需求参数
const handleViewRequirement = () => {
  emit('view-param', props.approvalData)
}

// 预览附件
const handlePreviewAttachment = () => {
  ElMessage.info('预览附件功能')
}

// 下载附件
const handleDownloadAttachment = () => {
  ElMessage.info('下载附件功能')
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
}

// 驳回
const handleReject = () => {
  commentType.value = 'reject'
  commentDialogVisible.value = true
}

// 通过
const handleApprove = () => {
  commentType.value = 'approve'
  commentDialogVisible.value = true
}
// 转交确认
const handleTransferConfirm = async () => {
  if (!transferFormRef.value) return

  try {
    await transferFormRef.value.validate()

    // 模拟转交API调用
    await new Promise((resolve) => setTimeout(resolve, 1000))

    ElMessage.success('转交成功')
    showTransfer.value = false
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    ElMessage.error('转交失败')
  }
}
// 取消审批意见弹窗
const handleCommentCancel = () => {
  commentDialogVisible.value = false
  Object.assign(commentForm, {
    comment: ''
  })
}
// 审批意见确认
const handleCommentConfirm = async () => {
  if (!commentFormRef.value) return
  
  try {
    await commentFormRef.value.validate()
    
    let apiResponse
    if (commentType.value === 'approve') {
      apiResponse = await approveApproval({
        requestId: props.approvalData.applicantId || props.approvalData.applicantId, // 使用正确的ID
        comment: commentForm.comment
      })
    } else if (commentType.value === 'reject') {
      apiResponse = await rejectApproval({
        requestId: props.approvalData.requestId,
        comment: commentForm.comment
      })
    }
    
    if (apiResponse && apiResponse.code === 200) {
      const action = commentType.value === 'approve' ? '通过' : '驳回'
      ElMessage.success(`审批${action}成功`)
      
      // 关闭审批意见弹窗
      commentDialogVisible.value = false
      
      // 重置表单并关闭主弹窗
      resetForms()
      dialogVisible.value = false
      
      // 通知父组件刷新数据
      emit('success')
    } else {
      throw new Error('提交')
    }
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('审批失败')
  }
}
</script>

<style lang="scss" scoped>

.approval-info {
  margin-bottom: 30px;
}

.approval-info h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  text-align: right;
}

.action-buttons .el-button {
  margin: 0 10px;
}
.info-item-with-link {
  display: flex;
  align-items: center;
  width: 100%;
}

.transfer-section {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.transfer-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.transfer-buttons {
  text-align: right;
  margin-top: 20px;
}

.transfer-buttons .el-button {
  margin-left: 10px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions-item__label) {
  font-weight: 600;
}
</style>
